package manager;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import member.MemberBean;
import book.RentalBean;

import common.DBManager;
import common.TableManager;

public class RentalListServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		resp.setCharacterEncoding("UTF-8");

		// ページ設定
		String pageStr = req.getParameter("page");
		int page;
		int max = 10;	// 1ページあたりの表示件数
		if(pageStr == null) {
			page = 1;
		} else {
			page = Integer.parseInt(pageStr);
		}
		int start = (page - 1) * max;

		// 担当者情報取得SQL文
		String sql = "select * from rentals order by id limit " + start + ", " + max;
		
		// 担当者件数取得SQL文
		String sqlCnt = "select count(*) as cnt from rentals";

		Connection con = null;
		Statement smt = null;

		try {
			con = DBManager.getConnection();
			smt = con.createStatement();
			ResultSet rs = smt.executeQuery(sql);

			List<RentalBean> list = new ArrayList<RentalBean>();
			List<MemberBean> listAppend = new ArrayList<MemberBean>();
			
			int i=1;

			while(rs.next()) {
				RentalBean rentals=(RentalBean)TableManager.getRecord(TableManager.RENTALS_TABLE, String.valueOf(i)).getBean();
				String IndexId=String.valueOf(rentals.getMemberId());
				System.out.println(IndexId);
				MemberBean members=(MemberBean)TableManager.getRecord(TableManager.MEMBERS_TABLE, IndexId).getBean();
				list.add(rentals);
				listAppend.add(members);
				i++;
			}
			req.setAttribute("list", list);
			req.setAttribute("listAppend", listAppend);

			rs = smt.executeQuery(sqlCnt);
			rs.next();
			Integer cnt = new Integer(rs.getInt("cnt"));
			req.setAttribute("cnt", cnt);

		}catch(NullPointerException e) {
			e.printStackTrace();
			req.setAttribute("list", null);
		}
		catch(SQLException e) {
			throw new ServletException(e);
		} finally {
			if(smt != null) {
				try {
					smt.close();
				} catch(SQLException ignore) {
					// none
				}
			}
			if(con != null) {
				try {
					con.close();
				} catch(SQLException ignore) {
					// none
				}
			}
		}
		req.setAttribute("page", page);
		req.getRequestDispatcher("/member/userMemberNotReturn.jsp").forward(req, resp);
	}
}
